#coding=utf-8

from common.import_common import *

from question.forms import QuestionForm
from image.util import handle_upload_image
from image.models import Image
from question.models import Question

from vote.forms import VoteForm

@login_required
def list(request, template_name="question/list.html"):
    questions = Question.objects.all()
    return render_to_response(template_name, {"questions": questions,},
                              context_instance=RequestContext(request))

@login_required   
def mine(request, template_name="question/list.html"):
    questions = Question.objects.filter(user=request.user)
    return render_to_response(template_name, {"questions": questions,},
                              context_instance=RequestContext(request))                   
                              
@login_required                              
def create(request, template_name="question/create.html"):
    if request.method == 'POST':
        form = QuestionForm(request, data=request.POST)
        if form.is_valid():
            file = request.FILES['photo']
            if file.size > settings.MAX_PHOTO_FILE_SIZE:
                message = u'上传文件大小不能超过2M'
                has_error = True
            else: 
                image =  handle_upload_image(request.user, request.FILES['photo'], Image.PHOTO)
                question = form.save(request.user, image)
                return HttpResponseRedirect("/question/list/")
                
   
    else:
        form = QuestionForm()
    return render_to_response(template_name, {"form":form,},
                                  context_instance=RequestContext(request))

@login_required
def detail(request, id, template_name="question/detail.html"):
    question = Question.objects.get(pk=id)
    from vote.models import Vote
    votes = Vote.objects.filter(question=question)
    form = VoteForm()
    if question.user == request.user:
        question.is_mine = True
    else:
        question.is_mine = False
    return render_to_response(template_name, {"question": question,"form":form, "votes":votes,},
                              context_instance=RequestContext(request))        
                              